<template>
  <div class="app-container">
    <el-card>
      <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
      >
        <el-form-item label="申请编号">
          <el-input
              v-model="queryParams.applyCode"
              placeholder="请输入申请编号"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="老人姓名">
          <el-input
              v-model="queryParams.applyName"
              placeholder="请输入老人姓名"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
              v-model="queryParams.reviewStatus"
              clearable
              placeholder="请选择审核状态"
              style="width: 240px"
          >
            <el-option
                v-for="dict in check_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="postList" stripe border max-height="500">
        <el-table-column label="申请编号" align="center" prop="applyCode"  width="200" />
        <el-table-column label="老人姓名" align="center" prop="applyName" width="100" />
        <el-table-column label="性别" align="center" width="100" >
          <template #default="scope">
        <span>
           {{sys_user_sex.find(item=>item.value==scope.row.sex)? sys_user_sex.find(item=>item.value==scope.row.sex).label:''}}

        </span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="center" prop="age"   width="100" />

        <el-table-column label="申请日期" align="center" prop="applyDate"  width="150" />

        <el-table-column label="家庭住址" align="center">
          <template #default="scope">
            <spna>{{scope.row.livingAddrProvinceName}}{{scope.row.livingAddrCityName}}{{scope.row.livingAddrCountyName}}{{scope.row.livingAddrStreetName}}{{scope.row.livingAddrCommunityName}}{{scope.row.livingDetailAddress}}
            </spna>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center"  width="120" >
          <template #default="scope">
            <span>
              {{check_status.find(item=>item.value==scope.row.reviewStatus)? check_status.find(item=>item.value==scope.row.reviewStatus).label:''}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
            class-name="small-padding" width="100">
          <template #default="scope">
            <el-button link type="primary" @click="check(scope.row)" v-if="scope.row.reviewStatus==='0'">审核</el-button>
            <el-button link type="primary"  @click="getInfo(scope.row)" v-else>查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.limit"
          @pagination="getList"
      />
    </el-card>
    <el-dialog
        v-model="open"
        :title="title"
        append-to-body
        width="900px"
        v-if="open"
        @close="cancel"
        :close-on-click-modal="false"
    >
    <info :show-btn="false" :formData="formData"></info>
     <div>
       <el-form ref="checkRef" :model="form" :rules="rules" label-width="120px" >
          <el-row>
               <el-col :span="12">
                 <el-form-item label="审核人姓名" prop="reviewerName">
                   <el-input v-model="form.reviewerName" placeholder="请输入审核人姓名" :disabled="!checkFlag" />
                 </el-form-item>
               </el-col>
              <el-col :span="12">
                <el-form-item label="审核结果" prop="reviewStatus">
                  <el-select v-model="form.reviewStatus" clearable placeholder="请选择审核结果" :disabled="!checkFlag" style="width: 100%">
                    <el-option label="通过" value="1"></el-option>
                    <el-option label="驳回" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="notes">
                <el-input
                    show-word-limit
                    maxlength="500"
                    v-model="form.notes"
                    :disabled="!checkFlag"
                    type="textarea"
                    :autosize="{ minRows: 4, maxRows: 10 }"
                    placeholder="如有驳回申请，请注明缘由"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="其他附件" style="font-weight: 700">
                <el-upload
                    style="width:100%"
                    v-model:file-list="fileList"
                    class="upload-demo"
                    :action="url"
                    :headers="upload.headers"
                    multiple
                    :on-remove="handleRemove"
                    :on-success="handleUploadSuccess"
                    :limit="10"
                    :on-exceed="handleExceed"
                >
                  <el-button type="primary"  link >添加附件</el-button>

                </el-upload>
              </el-form-item>
            </el-col>

          </el-row>
       </el-form>
     </div>
      <template #footer v-if="checkFlag">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      <template #footer v-else>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改岗位对话框 -->
  </div>
</template>

<script setup name="check">

  const { proxy } = getCurrentInstance();
  const { sys_normal_disable, sys_user_sex, check_status } = proxy.useDict(
      "sys_normal_disable",
      "sys_user_sex",
      "check_status",
  );

  import info from './../apply/info.vue'
  import {
    homeBedApplyReviewList,
    homeBedApplyInfo,
    homeBedApplyUpdateReviewInfo
  } from '@/api/homebedsign/index'
  import { debounce } from "@/utils/debounce.js";
  import { getToken } from "@/utils/auth";

  const showSearch = ref(true);
  const loading = ref(true);
  const postList = ref([]);
  const open = ref(false);
  const title = ref("新增服务项目");
  const fileList = ref([])

  const total = ref(0);
  const checkFlag = ref(true);
  const url = ref(process.env.VUE_APP_BASE_API + "/file/upload")
  const upload = reactive({
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
  });

  const data = reactive({
    form: {},
    formData: {},
    queryParams: {
      page: 1,
      limit: 10,
      applyName: undefined,
      reviewStatus: undefined,
      applyCode: undefined
    },
    rules: {
      reviewerName: [
        { required: true, message: '请输入审核人姓名', trigger: 'blur' },
        { required: true, min: 1, max: 10, message: '审核人姓名不超过10个字符', trigger: 'blur' }
      ],
      reviewStatus: [
        { required: true, message: '请选择审核人结果', trigger: 'change' }
      ],
      notes: [
        { required: false, min: 0, max: 500, message: '备注不超过500个字符', trigger: 'blur' }
      ]
    }
  });

  const { queryParams, form, rules, formData } = toRefs(data);

  function cancel() {
    open.value = false;
    form.value.notes = ''
    form.value.reviewStatus = ''
    fileList.value = []
    proxy.resetForm("checkRef");
  }

  function handleExceed(files, uploadFiles){
    proxy.$modal.msgError("附近最多上传10个");
  }

  function handleRemove(files, fileList) {
    let arr = [];
    for (let i in fileList) {
      console.log(fileList[i]);
      if (fileList[i].response) {
        arr.push({
          name: fileList[i].response.data.name,
          attachmentUrl: fileList[i].response.data.url,
        });
      } else {
        arr.push({
          name: fileList[i].name,
          attachmentUrl: fileList[i].url,
        });
      }
    }
    form.value.otherAttachmentList = arr;
  }

  function handleUploadSuccess(res, file, fileList) {
    let arr = [];
    for (let i in fileList) {
      if (fileList[i].response) {
        arr.push({
          name: fileList[i].response.data.name,
          attachmentUrl: fileList[i].response.data.url,
        });
      } else {
        arr.push({
          name: fileList[i].name,
          attachmentUrl: fileList[i].url,
        });
      }
    }
    form.value.otherAttachmentList = arr;
  }

  function check(data) {
    homeBedApplyInfo(data.id).then(res=>{
      formData.value=res.homeBedApply
      open.value=true
      checkFlag.value=true
      title.value='审核床位申请'
    })
  }

  function getInfo (data) {
    homeBedApplyInfo(data.id).then(res=>{
      formData.value=res.homeBedApply
      form.value.reviewerName=res.homeBedApply.reviewerName
      form.value.notes=res.homeBedApply.notes
      form.value.reviewStatus=res.homeBedApply.reviewStatus
      fileList.value=res.homeBedApply.otherAttachmentList
      open.value=true
      checkFlag.value=false
      title.value='查看审核床位申请'
    })
  }

  /** 查询岗位列表 */
  function getList() {
    loading.value = true;
    homeBedApplyReviewList(queryParams.value).then((response) => {
      postList.value = response.page.list;
      total.value = response.page.totalCount;
      loading.value = false;
    });
  }

  /** 提交按钮 */
  const submitFormDebounceHandler = debounce(submitForm, 500);

  function submitForm() {
    proxy.$refs["checkRef"].validate((valid) => {

      if (valid) {
        let obj = {
          id: formData.value.id,
          homeBedApplyId: formData.value.id,
          ...form.value
        }

        homeBedApplyUpdateReviewInfo(obj).then((response) => {
          proxy.$modal.msgSuccess("操作成功")
          getList();
          cancel()
        });
      }
    });
  }

  function handleQuery() {
    getList();
  }

  function resetQuery() {
    queryParams.value = {
      page: 1,
      limit: 10,
      applyCode: undefined,
      applyName: undefined,
      applyStatus: undefined,
      isDraft:1
    };
    getList();
  }

  function handleDelete(row) {
    proxy.$modal
        .confirm("是否确认删除该数据项？")
        .then(function () {
          return serviceItemDel([row.id]);
        })
        .then(() => {
          getList();
          proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
  }
  function addDeviceTypes() {
    title.value = "新增服务项目";
    open.value = true;
  }

  getList();
</script>
